import React, { useState, useRef, useEffect, KeyboardEvent, memo, useCallback } from 'react';
import { Button, Upload, Tooltip } from 'antd';
import {
  SendOutlined,
  PaperClipOutlined,
  AudioOutlined,
  StopOutlined
} from '@ant-design/icons';
import { useBreakpoint } from '../../../hooks/useBreakpoint';
import { Hide } from '../../../components/Responsive/ResponsiveExports';
import './style.css';

interface MessageInputProps {
  onSend: (message: string) => void;
  disabled?: boolean;
}

const MessageInput: React.FC<MessageInputProps> = memo(({ onSend, disabled = false }) => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  const [message, setMessage] = useState('');
  const [isRecording, setIsRecording] = useState(false);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // Auto-resize textarea based on content (debounced for performance)
  const adjustTextareaHeight = useCallback(() => {
    const textarea = textareaRef.current;
    if (textarea) {
      textarea.style.height = 'auto';
      const maxHeight = isMobile ? 120 : 200; // 移动端最大5行，桌面端更多
      const newHeight = Math.min(textarea.scrollHeight, maxHeight);
      textarea.style.height = `${newHeight}px`;
    }
  }, [isMobile]);

  useEffect(() => {
    adjustTextareaHeight();
  }, [message, isMobile]);

  // 移动端键盘弹出时滚动输入框到可视区域
  useEffect(() => {
    if (isMobile && textareaRef.current) {
      const textarea = textareaRef.current;

      const handleFocus = () => {
        // 延迟等待键盘动画完成
        setTimeout(() => {
          textarea.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }, 300);
      };

      textarea.addEventListener('focus', handleFocus);
      return () => textarea.removeEventListener('focus', handleFocus);
    }
  }, [isMobile]);

  // Handle Ctrl+Enter shortcut
  const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
      e.preventDefault();
      handleSend();
    }
  };

  const handleSend = () => {
    const trimmedMessage = message.trim();
    if (trimmedMessage && !disabled) {
      onSend(trimmedMessage);
      setMessage('');
      // Reset textarea height
      if (textareaRef.current) {
        textareaRef.current.style.height = 'auto';
      }
    }
  };

  const handleVoiceInput = () => {
    if (isRecording) {
      // Stop recording
      setIsRecording(false);
      // TODO: Implement voice recording stop logic
    } else {
      // Start recording
      setIsRecording(true);
      // TODO: Implement voice recording start logic
    }
  };

  const handleFileUpload = (info: any) => {
    // TODO: Implement file upload logic
    console.log('File upload:', info);
  };

  return (
    <div className="message-input-container" ref={containerRef}>
      <div className="message-input-wrapper">
        {/* 左侧工具按钮（桌面端显示更多） */}
        <Hide breakpoint="mobile">
          <div className="message-input-actions-left">
            <Upload
              beforeUpload={() => false}
              onChange={handleFileUpload}
              showUploadList={false}
              disabled={disabled}
            >
              <Tooltip title="上传文件">
                <Button
                  type="text"
                  icon={<PaperClipOutlined />}
                  disabled={disabled}
                  className="input-action-button"
                />
              </Tooltip>
            </Upload>
          </div>
        </Hide>

        <div className="message-input-main">
          <textarea
            ref={textareaRef}
            className={`message-input-textarea ${isMobile ? 'mobile' : ''}`}
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={disabled ? "AI 正在回复中..." : (isMobile ? "输入消息..." : "输入消息... (Ctrl+Enter 发送)")}
            disabled={disabled}
            rows={1}
            style={{
              minHeight: isMobile ? '44px' : '48px', // 触摸友好最小高度
              fontSize: isMobile ? '16px' : '14px', // 移动端16px防止iOS自动缩放
            }}
          />
        </div>

        <div className="message-input-actions-right">
          {/* 语音输入按钮（移动端可选） */}
          <Hide breakpoint="mobile">
            <Tooltip title={isRecording ? "停止录音" : "语音输入"}>
              <Button
                type="text"
                icon={isRecording ? <StopOutlined /> : <AudioOutlined />}
                onClick={handleVoiceInput}
                disabled={disabled}
                className={`input-action-button ${isRecording ? 'recording' : ''}`}
              />
            </Tooltip>
          </Hide>

          {/* 发送按钮（始终可见） */}
          <Tooltip title={isMobile ? "" : "发送 (Ctrl+Enter)"}>
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={handleSend}
              disabled={disabled || !message.trim()}
              className={`send-button ${isMobile ? 'h-touch' : ''}`}
              style={{
                minWidth: isMobile ? '44px' : 'auto',
                minHeight: isMobile ? '44px' : 'auto',
              }}
            >
              {!isMobile && <span style={{ marginLeft: '4px' }}>发送</span>}
            </Button>
          </Tooltip>
        </div>
      </div>

      {/* 状态指示器和字符计数 */}
      <div className="message-input-status">
        {disabled && (
          <span className="status-indicator">AI 正在输入...</span>
        )}
        {isRecording && (
          <span className="status-indicator recording">正在录音...</span>
        )}
        {message.length > 0 && !disabled && (
          <span className={`character-count ${isMobile ? 'mobile' : ''}`}>
            {message.length} 字符
          </span>
        )}
      </div>
    </div>
  );
});

MessageInput.displayName = 'MessageInput';

export default MessageInput;